<?php
namespace App\Admin\Controllers\OverSeasBa;

use App\Admin\Ajax\OverSeasBa\BoxFnSkuAjax;
use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysIArea;
use App\Models\OverSeasBa\InventoryBoxFNSku;
use App\Models\OverSeasBa\Warehouse;
use App\Models\OverSeasBa\WarehouseGroup;
use App\Models\Product\ProductClassify;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class BoxInventoryFnSkuController extends AdminController{

    protected $title = '中转FNSKU库存';

    protected $filters = [
        'account_id' => null,
        'group_id' => null,
        'warehouse_id' => null,
        'area_id' => null,
        'country_id' => null,
        'fnsku' => null,
        'classify_id' => null,
        'sku' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['account_id'] = getOptions(SysPlatAccount::options(),$this->filters['account_id']);
        $filtersBlade['group_id'] = getOptions(WarehouseGroup::options(),$this->filters['group_id']);
        $filtersBlade['warehouse_id'] = getOptions(Warehouse::options(),$this->filters['warehouse_id']);
        $filtersBlade['area_id'] = getOptions(SysIArea::options(),$this->filters['area_id']);
        $filtersBlade['country_id'] = getOptions(AmazonCountry::options(),$this->filters['country_id']);
        $filtersBlade['fnsku'] = $this->filters['fnsku'];
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $filtersBlade['sku'] = $this->filters['sku'];
        $downloadUrl = '/xqc/overseas-ba/box-fnsku-in-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('overseas-ba.box-fnsku-in.index', compact('paginator','action','filtersBlade','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = InventoryBoxFNSku::query();
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'group_id'){
                $query->whereHas('warehouse', function ($query) use($filter){
                    $query->where('group_id', $filter);
                });
            }
            if($field == 'area_id'){
                $query->whereHas('warehouse', function ($query) use($filter){
                    $query->where('area_id', $filter);
                });
            }
            if($field == 'sku'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'classify_id'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('classify_id', $filter);
                });
            }
            if($field == 'country_id'){
                $query->whereHas('warehouse', function ($query) use($filter){
                    $query->where('country_id', $filter);
                });
            }
            if(in_array($field,['account_id','warehouse_id','fnsku'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new BoxFnSkuAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['账号','海外仓','仓库','站点','国家','FNSKU','产品SKU','品类','在库','在途','保留','产品名称'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="中转FNSKU库存.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->orderBy('id','DESC')->chunk(500, function ($re) use ($fp){
                $data = $this->__getData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

    private function __getData($re)
    {
        $account = [];
        $area = [];
        $group = [];
        $country = [];
        foreach ($re as $row){
            $accountId = $row->account_id ?? -1;
            if(!array_key_exists($accountId,$account)){
                $account[$accountId] = SysPlatAccount::getAccountById($accountId);
            }
            $groupId = $row->warehouse->group_id ?? -1;
            if(!array_key_exists($groupId,$group)){
                $group[$groupId] = WarehouseGroup::getNameById($groupId);
            }
            $areaId = $row->warehouse->area_id ?? -1;
            if(!array_key_exists($areaId,$area)){
                $area[$areaId] = SysArea::getSysAreaById($areaId);
            }
            $countryId = $row->warehouse->country_id ?? 0;
            if(!array_key_exists($countryId,$country)){
                $country[$countryId] = SysCountry::getCountryById($countryId);
            }
            $temp = [
                $account[$accountId],
                $group[$groupId],
                $row->warehouse->w_code ?? '',
                $area[$areaId],
                $country[$countryId],
                $row->fnsku,
                $row->sku->psku_code ?? '',
                $row->skuClassify->title ?? '',
                $row->instant,
                $row->transit,
                $row->reserve,
                $row->sku->psku_cn ?? '',
            ];
            yield $temp;
        }
    }
}
